//
//  ZWHomeTableViewController.swift
//  ZWWeibo
//
//  Created by flyiron on 16/4/16.
//  Copyright © 2016年 flyiron. All rights reserved.
//

import UIKit

class ZWHomeTableViewController: ZWVisitorViewController {
    
    let identifier: String = "cell"
    
//    var statusList:[ZWStatuses]?
    //当前控制器的ViewModel
    var viewModel:ZWStatusesListViewModel = ZWStatusesListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLogin {
            visitorView.setValueForView(nil , iconImageName: nil )
            return
        }
        setupUI()
        loadData()
    }
    
    private func setupUI(){
        tableView.backgroundColor = UIColor(white: 245/255, alpha: 1)
        tableView.registerClass(ZWHomeTableViewCell.self, forCellReuseIdentifier: identifier)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 250
        tableView.separatorStyle = .None
        tableView.tableFooterView = pullupView
        tableView.addSubview(zwrefreshControl)
        zwrefreshControl.addTarget(self, action: #selector(ZWHomeTableViewController.loadData), forControlEvents: .ValueChanged)
        
      
    }
    
    
   @objc private func loadData(){
        viewModel.loadData(pullupView.isAnimating()) { (isSucess) -> () in
            if isSucess{
                self.tableView.reloadData()
            }else{
                print("数据获取失败")
            }
            self.pullupView.stopAnimating()
            self.zwrefreshControl.endRefreshing()
        }
    }
    private lazy var pullupView:UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.orangeColor()
        return view
    }()
    
    private lazy var zwrefreshControl:ZWRefreshControl = ZWRefreshControl()

}

extension ZWHomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
        return viewModel.statusViewModelList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! ZWHomeTableViewCell
//        cell.textLabel?.text = viewModel.statusList![indexPath.row].text
//        print(indexPath.row)
        cell.statusViewModel = viewModel.statusViewModelList![indexPath.row]
        return cell
    }
    
    //上拉加载
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == (viewModel.statusViewModelList?.count)! - 1 && !pullupView.isAnimating(){
            self.pullupView.startAnimating()
            loadData()
            
        }
    }
    
    }

